package com.lzh.runke.core.web_base.enums;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.lzh.runke.core.web_base.enums.deserializer.EnumDeserializer;

/**
 * 枚举基类
 *
 * @author liyuanxi
 * @date 2018/12/25 14:56
 */
@JsonDeserialize(using = EnumDeserializer.class)
public interface BaseEnum<V> {

    V getValue();

    default String getText() {
        return null;
    }

    String getName();

    /**
     * 根据枚举value生成枚举
     *
     * @param value
     * @param clazz
     * @param <E>
     * @return
     * @author liyuanxi
     * @date 2019/4/17 11:47
     */
    static <E extends Enum<E> & BaseEnum> E valueOf(Object value, Class<E> clazz) {
        E em;
        E[] enums = clazz.getEnumConstants();
        String enumName = null;
        for (BaseEnum e : enums) {
            if (e.getValue().equals(value)) {
                enumName = e.getName();
            }
        }
        if (null != enumName) {
            em = Enum.valueOf(clazz, enumName);
        } else {
            throw new RuntimeException(value + "未匹配上对应的枚举");
        }
        return em;
    }

    /**
     * 根据枚举name生成枚举类型
     *
     * @param name  枚举name字段值
     * @param clazz 枚举类
     * @param <E>
     * @return
     * @author liyuanxi
     * @date 2019/4/17 11:47
     */
    static <E extends Enum<E> & BaseEnum> E nameOf(String name, Class<E> clazz) {
        return Enum.valueOf(clazz, name);
    }
}
